<?php
session_start();
/* Complet (Autocompletion through Graph Databases)
 *  Copyright (C) 2012  Paul Wagner, Till Speicher
 *
 *  This program is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; either version 3 of the License, or (at your
 *  option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *  for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, see <http:/* www.gnu.org/licenses/>.
*/

/*
 * WHAT THIS SCRIPT DOES:
 *  + Its a wrapper to make Tomcat-Server independent from a query-response
 *  + It redirects to the correct port when a language is selected
 *  + It handles userdata and sessioninfos
 *  + It handles all kinds of precalculations before a complet request will be triggered
 *      - Append session-/userinfos to request
 *      - Do logging
 */

// CONFIG_VARS
$DO_LOGGING = true;
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'typolog';

// Decode recieved json
$obj = json_decode($_POST['json']);

// Save uid (mail adress or device id) in session
if(!isset($_SESSION['uid'])){
    if(property_exists($obj, 'uid') && property_exists($obj, 'uid_type') && $obj->uid != ''){
        $_SESSION['uid'] = $obj->uid;
        $_SESSION['uid_type'] = $obj->uid_type;
    }else{
        $_SESSION['uid'] = $_COOKIE['PHPSESSID'];
        $_SESSION['uid_type'] = 'SESSION';
    }
}

// If last request has been primitive, do this as well, except we have a new word (offset <= 2)
// If primitive is always set manually, last primitive will never be used...
if(isset($_SESSION['lastprimitive'])){
    $obj->primitive = $_SESSION['lastprimitive'];
    if(strlen($obj->offset) <= 2){
        $obj->primitive = false;
        $_SESSION['lastprimitive'] = false;
    }
}else{
    if(!$obj->primitive){
        $_SESSION['lastprimitive'] = false;
    }
}

// Do logging
if($DO_LOGGING){
    $mysqli = new mysqli($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);

    // Get or create session
    $slfnr = 0;
    $result = $mysqli->query("SELECT slfnr FROM session WHERE type='".$_SESSION["uid_type"]."' and id='".$_SESSION['uid']."'");
    if ($result->num_rows == 0) {
        // Create new session
        $result2 = $mysqli->query("INSERT INTO session(id, type) VALUES ('".$_SESSION['uid']."', '".$_SESSION["uid_type"]."')");
        $slfnr = $mysqli->insert_id;
    }else{
        $row = $result->fetch_object();
        $slfnr = $row->slfnr;
    }

    // Insert logging
    $newword = false;
    $selected = 0;
    // If offset is just one letter, we have a new word
    if(strlen($obj->offset) == 1){
        $newword = true;
    }
//    // If new offset fits, but is longer than old offset
//    if(strlen($obj->offset) > strlen($_SESSION['last'])+1  &&  strpos($_SESSION['last'], $obj->offset) == 0){
//        $selected = true;
//    }
//    // Or if old offset fits current last word and is shorter
//    if(count($obj->words) > 0 && $_SESSION['last']!=''){
//        $word = $obj->words[count($obj->words)-1];
//        if(strlen($word) > strlen($_SESSION['last'])+1  &&  strpos($_SESSION['last'], $word) == 0){
//            $selected = true;
//        }
//        echo $_SESSION['last'];
//    }
//    if($selected)
//        $selected = 1;
//    else
//        $selected = 0;
    if($newword)
        $newword = 1;
    else
        $newword = 0;
    $result3 = $mysqli->query("INSERT INTO log(slfnr, words, offset, newword, selected) VALUES (".$slfnr.", '".implode(" ", $obj->words)."', '".$obj->offset."', ".$newword.", ".$selected.")");

}

// Save old offset
$_SESSION['last'] = $obj->offset;

$_POST['json'] = json_encode($obj);
//$result = post_request('http://typology.de/complet/complet.jsp', $_POST);
$result = post_request('http://localhost/Completion_TomcatSvr/complet.jsp', $_POST);

// If primitive setting has changed from false to true, save it
$objres = json_decode($result['content']);
if(!$obj->primitive && $objres->primitive){
    $_SESSION['lastprimitive'] = true;
}

echo $result['content'];

function post_request($url, $data, $referer='') {

    // Convert the data array into URL Parameters like a=b&foo=bar etc.
    $data = http_build_query($data);

    // parse the given URL
    $url = parse_url($url);

    if ($url['scheme'] != 'http') {
        die('Error: Only HTTP request are supported !');
    }

    // extract host and path:
    $host = $url['host'];
    $path = $url['path'];

    // open a socket connection on port 8080 - timeout: 30 sec
    $fp = fsockopen($host, 8084, $errno, $errstr, 30);

    if ($fp) {

        // send the request headers:
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");

        if ($referer != '')
            fputs($fp, "Referer: $referer\r\n");

        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: " . strlen($data) . "\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data);

        $result = '';
        while (!feof($fp)) {
            // receive the results of the request
            $result .= fgets($fp, 128);
        }
    } else {
        return array(
            'status' => 'err',
            'error' => "$errstr ($errno)"
        );
    }

    // close the socket connection:
    fclose($fp);

    // split the result header from the content
    $result = explode("\r\n\r\n", $result, 2);

    $header = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';

    // return as structured array:
    return array(
        'status' => 'ok',
        'header' => $header,
        'content' => $content
    );
}
?>